package gacl.servlet.study;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CookieDemo02
 */
@WebServlet("/CookieDemo02")
/**
 * @author gacl
 * 删除cookie
 */
public class CookieDemo02 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieDemo02() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		//创建一个名字为lastAccessTime的cookie
		Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
		//将cookie的有效期设置为0，命令浏览器删除该cookie
		cookie.setMaxAge(30);
		response.addCookie(cookie);
		
		Cookie cookie1 = new Cookie("userName", URLEncoder.encode("孤傲苍狼", "UTF-8"));
		cookie.setMaxAge(30);
		response.addCookie(cookie1);
		
		
		 //获取浏览器访问访问服务器时传递过来的cookie数组
		Cookie[] cookies = request.getCookies();
		if(cookies != null) {
			for(int i = 0; i < cookies.length; i++) {
				Cookie cookie2 = cookies[i];
				//if(cookie2.getName().equals("userName")) {
					String userName = URLDecoder.decode(cookies[i].getValue(), "UTF-8");
					System.out.println("userName:"+userName);
				//}
			}
		}else {
			System.out.println("这是您第一次访问本站");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
